#ifndef COMMON_H
#define COMMON_H

#ifdef __cplusplus
extern "C" {
#endif

//std
#include <stdlib.h>
#include <stdint.h>
//ffmpeg
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
//pthread
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#include "easyvid.h"

struct IVidFrame
{
    void* data;
    sem_t read_ok;
    sem_t write_ok;
};

struct IVid
{
    int used;
    int index;
    VidSource* vsrc;
    double frame_time;
    double fps;
    int frame_counter;
    //av
    AVFormatContext* fc;
    AVCodecContext* cc;
    AVPacket pkt;
    int video_stream;
    AVFrame* frame_yuv;
    AVFrame* frame_rgb;
    uint8_t* buffer;
    int buffer_size;
    //src and dst frame info
    int src_width;
    int src_height;
    enum PixelFormat src_format;
    int dst_width;
    int dst_height;
    enum PixelFormat dst_format;
    void* dst_data;
    //thread
    pthread_t thr;
    int thr_running;
    int thr_stop;
    //fifo
    struct IVidFrame* fifo_frames;
    int fifo_depth;
    int fifo_counter;
    //msg
    VidMsg msg;
    int msg_param;
    pthread_mutex_t msg_mutex;
};

void vid_init(struct IVid* vid, int index);
int vid_read_frame(struct IVid* vid, void* data);

// stream
void stream_start(struct IVid* vid);
void stream_stop(struct IVid* vid);
void* stream_running(void* arg);

// utils
void img_convert(AVPicture *dst, int dst_pix_fmt, const AVPicture *src, int pix_fmt,
                int src_w, int src_h, int dst_w, int dst_h);
void convert_frame_data(void* data_OUT, int width, int height, int bpp, void* data_IN);
int min_pow2(int x);

#ifdef __cplusplus
}
#endif

#endif // COMMON_H
